package com.sun.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;

@Controller
public class FileDownController {

    /**
     * 显示要下载的文件
     */
    @RequestMapping("/showDownFiles")
    public String show(HttpServletRequest request, Model model) {
        //获取真实路径地址，默认路径为项目的根目录
        String realpath = request.getServletContext().getRealPath("/WEB-INF/file/");
        System.out.println(realpath);
        //
        File dir = new File(realpath);
        File[] files = dir.listFiles();
        System.out.println(files);
        // 获取该目录下的所有文件名
        ArrayList<String> fileName = new ArrayList<String>();
        if (files != null) {
            for (File file : files) {
                fileName.add(file.getName());
            }
        }
        model.addAttribute("files", fileName);
        return "showDownFiles";
    }


    @RequestMapping("down")
    public ResponseEntity<byte[]> download(@RequestParam String filename, HttpServletRequest request, HttpServletResponse response){
        //获取真实路径地址，默认路径为项目的根目录
        String realpath = request.getServletContext().getRealPath("/WEB-INF/file/");

        //读取文件
        FileInputStream fileInputStream = null;
        byte[] b= new byte[0];
        try {
            fileInputStream = new FileInputStream(realpath + filename);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {

                if (fileInputStream != null) {
                    b = new byte[fileInputStream.available()];
                    fileInputStream.read(b);
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("Content-Disposition", "attachment;filename="+filename);
        return new ResponseEntity<byte[]>(b,httpHeaders, HttpStatus.OK);
    }
}
